<template>
  <GlobalDrawer
    v-model="visible"
    :title="formTitle"
    size="80%"
    :show-footer-buttons="true"
    @confirm="handleSubmit"
  >
    <el-form
      ref="formRef"
      :model="nonLawsuitForm"
      :rules="nonLawsuitRules"
      label-width="100px"
      v-loading="loading"
    >
      <!-- 引入公共表单 -->
      <OrderCommonForm
        ref="commonFormRef"
        :customer-id="props.customerId"
        :order-data="props.orderId ? orderData : {}"
      />

      <el-divider content-position="left">非诉讼订单信息</el-divider>

      <!-- 非诉讼订单特有字段 -->
      <el-form-item label="服务类型" prop="service_type">
        <el-radio-group v-model="nonLawsuitForm.service_type">
          <el-radio :label="1">单次服务</el-radio>
          <el-radio :label="2">套餐服务</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="套餐类型" prop="package_type" v-if="nonLawsuitForm.service_type === 2">
        <el-select v-model="nonLawsuitForm.package_type" placeholder="请选择套餐类型">
          <el-option :label="'基础套餐'" :value="1"></el-option>
          <el-option :label="'标准版套餐'" :value="2"></el-option>
          <el-option :label="'高级套餐'" :value="3"></el-option>
          <el-option :label="'定制套餐'" :value="4"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="服务数量" prop="service_count" v-if="nonLawsuitForm.service_type === 1">
        <el-input-number v-model="nonLawsuitForm.service_count" :min="1" style="width: 100%" />
      </el-form-item>

      <el-form-item label="服务期限" prop="service_period">
        <el-date-picker
          v-model="nonLawsuitForm.service_period"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="收费方式" prop="fee_type">
        <el-radio-group v-model="nonLawsuitForm.fee_type">
          <el-radio :label="1">一次性收费</el-radio>
          <el-radio :label="2">分期收费</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="收费周期" prop="fee_cycle" v-if="nonLawsuitForm.fee_type === 2">
        <el-select v-model="nonLawsuitForm.fee_cycle" placeholder="请选择收费周期">
          <el-option :label="'月'" :value="1"></el-option>
          <el-option :label="'季'" :value="2"></el-option>
          <el-option :label="'半年'" :value="3"></el-option>
          <el-option :label="'年'" :value="4"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="服务项目" prop="service_items">
        <el-checkbox-group v-model="nonLawsuitForm.service_items">
          <el-checkbox :label="1">合同审查</el-checkbox>
          <el-checkbox :label="2">合同起草</el-checkbox>
          <el-checkbox :label="3">法律顾问</el-checkbox>
          <el-checkbox :label="4">法律意见</el-checkbox>
          <el-checkbox :label="5">法律尽职调查</el-checkbox>
          <el-checkbox :label="6">法律培训</el-checkbox>
          <el-checkbox :label="7">商务谈判</el-checkbox>
          <el-checkbox :label="8">知识产权</el-checkbox>
          <el-checkbox :label="9">公司设立</el-checkbox>
          <el-checkbox :label="10">股权架构</el-checkbox>
          <el-checkbox :label="11">公司并购</el-checkbox>
          <el-checkbox :label="12">投融资</el-checkbox>
          <el-checkbox :label="13">税务筹划</el-checkbox>
          <el-checkbox :label="14">其他服务</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <el-form-item v-if="nonLawsuitForm.service_items.includes(14)" label="其他服务">
        <el-input v-model="nonLawsuitForm.service_items_other" placeholder="请输入其他服务内容" />
      </el-form-item>

      <el-form-item label="服务频次" v-if="nonLawsuitForm.service_type === 2">
        <el-input
          v-model="nonLawsuitForm.service_frequency"
          placeholder="请输入服务频次（如：每月至少1次）"
        />
      </el-form-item>

      <el-form-item label="响应时间" v-if="nonLawsuitForm.service_type === 2">
        <el-input
          v-model="nonLawsuitForm.response_time"
          placeholder="请输入响应时间（如：24小时内）"
        />
      </el-form-item>

      <el-form-item label="服务人员安排">
        <el-input v-model="nonLawsuitForm.staff_arrangement" placeholder="请输入服务人员安排" />
      </el-form-item>

      <el-form-item label="服务要求">
        <el-input
          v-model="nonLawsuitForm.service_requirements"
          type="textarea"
          :rows="4"
          placeholder="请输入具体服务要求"
        />
      </el-form-item>

      <el-form-item label="交付物">
        <el-input
          v-model="nonLawsuitForm.deliverables"
          type="textarea"
          :rows="4"
          placeholder="请输入预期交付物"
        />
      </el-form-item>

      <el-form-item label="备注">
        <el-input
          v-model="nonLawsuitForm.remark"
          type="textarea"
          :rows="2"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'
  import OrderCommonForm from './common/OrderCommonForm.vue'
  import { nonLawsuitOrderApi } from '@/api/crm/nonLawsuitOrderApi'

  // Props定义
  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: Number,
      default: 0,
    },
    customerId: {
      type: Number,
      default: 0,
    },
  })

  // Emits定义
  const emit = defineEmits(['update:modelValue', 'success'])

  // 响应式数据
  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const loading = ref(false)
  const formRef = ref()
  const commonFormRef = ref()
  const orderData = ref({})

  // 非诉讼订单特有表单数据
  const nonLawsuitForm = reactive({
    service_type: 1,
    package_type: 1,
    service_count: 1,
    service_period: [] as Date[],
    fee_type: 1,
    fee_cycle: 1,
    service_items: [] as number[],
    service_items_other: '',
    service_frequency: '',
    response_time: '',
    staff_arrangement: '',
    service_requirements: '',
    deliverables: '',
    remark: '',
  })

  // 非诉讼订单特有验证规则
  const nonLawsuitRules = {
    service_type: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
    package_type: [
      {
        required: () => nonLawsuitForm.service_type === 2,
        message: '请选择套餐类型',
        trigger: 'change',
      },
    ],
    service_count: [
      {
        required: () => nonLawsuitForm.service_type === 1,
        message: '请输入服务数量',
        trigger: 'blur',
      },
    ],
    service_period: [{ required: true, message: '请选择服务期限', trigger: 'change' }],
    fee_type: [{ required: true, message: '请选择收费方式', trigger: 'change' }],
    fee_cycle: [
      {
        required: () => nonLawsuitForm.fee_type === 2,
        message: '请选择收费周期',
        trigger: 'change',
      },
    ],
    service_items: [
      { required: true, message: '请选择服务项目', trigger: 'change' },
      { type: 'array', min: 1, message: '至少选择一个服务项目', trigger: 'change' },
    ],
  }

  // 表单标题
  const formTitle = computed(() => {
    return props.orderId ? '编辑非诉讼订单' : '新增非诉讼订单'
  })

  // 获取订单详情
  const getOrderDetail = async () => {
    if (!props.orderId) return

    loading.value = true
    try {
      const res = await nonLawsuitOrderApi.detail(props.orderId)
      orderData.value = res.data

      // 填充非诉讼特有数据
      Object.keys(nonLawsuitForm).forEach(key => {
        if ((res.data as any)[key] !== undefined) {
          ;(nonLawsuitForm as any)[key] = (res.data as any)[key]
        }
      })

      // 处理日期格式
      if ((res.data as any).service_period_start && (res.data as any).service_period_end) {
        nonLawsuitForm.service_period = [
          new Date((res.data as any).service_period_start),
          new Date((res.data as any).service_period_end),
        ]
      }

      // 等待公共表单初始化完成
      await nextTick()
      if (commonFormRef.value) {
        commonFormRef.value.initData()
      }
    } catch (error) {
      console.error('获取订单详情失败:', error)
      ElMessage.error('获取订单详情失败')
    } finally {
      loading.value = false
    }
  }

  // 提交表单
  const handleSubmit = async () => {
    // 验证公共表单
    if (commonFormRef.value && commonFormRef.value.formRef) {
      const valid = await commonFormRef.value.formRef.validate()
      if (!valid) return
    }

    // 验证非诉讼特有表单
    if (!formRef.value) return
    const valid = await formRef.value.validate()
    if (!valid) return

    loading.value = true
    try {
      // 获取公共表单数据
      const commonData = commonFormRef.value?.getFormData() || {}

      // 准备日期范围数据
      let servicePeriodData = {}
      if (nonLawsuitForm.service_period && nonLawsuitForm.service_period.length === 2) {
        servicePeriodData = {
          service_period_start: nonLawsuitForm.service_period[0],
          service_period_end: nonLawsuitForm.service_period[1],
        }
      }

      // 合并数据
      const submitData = {
        ...commonData,
        ...nonLawsuitForm,
        ...servicePeriodData,
        order_category: 1, // 非诉讼订单类别
        customer_id: props.customerId,
        opportunity_id: props.orderId || 0,
      }

      // 删除不需要的字段
      delete submitData.service_period

      // 根据是否有订单ID决定是新增还是编辑
      if (props.orderId) {
        await nonLawsuitOrderApi.update(props.orderId, submitData)
        ElMessage.success('更新成功')
      } else {
        await nonLawsuitOrderApi.create(submitData)
        ElMessage.success('创建成功')
      }

      // 触发成功事件
      emit('success')
      handleClose()
    } catch (error) {
      console.error('提交失败:', error)
      ElMessage.error('提交失败，请重试')
    } finally {
      loading.value = false
    }
  }

  // 关闭抽屉
  const handleClose = () => {
    visible.value = false
    // 重置表单
    resetForm()
  }

  // 重置表单
  const resetForm = () => {
    if (formRef.value) {
      formRef.value.resetFields()
    }

    if (commonFormRef.value) {
      commonFormRef.value.resetForm()
    }

    // 重置非诉讼特有表单
    nonLawsuitForm.service_type = 1
    nonLawsuitForm.package_type = 1
    nonLawsuitForm.service_count = 1
    nonLawsuitForm.service_period = []
    nonLawsuitForm.fee_type = 1
    nonLawsuitForm.fee_cycle = 1
    nonLawsuitForm.service_items = []
    nonLawsuitForm.service_items_other = ''
    nonLawsuitForm.service_frequency = ''
    nonLawsuitForm.response_time = ''
    nonLawsuitForm.staff_arrangement = ''
    nonLawsuitForm.service_requirements = ''
    nonLawsuitForm.deliverables = ''
    nonLawsuitForm.remark = ''
  }

  // 组件挂载时
  onMounted(() => {
    // 如果打开时就有订单ID，获取订单详情
    if (props.modelValue && props.orderId) {
      getOrderDetail()
    }
  })
</script>

<style scoped>
  /* 可以添加特定样式 */
</style>
